The Story of Block Chain

BitCoin Basis

* Block Chain Version 1.0
* What is Bitcoin?
    * Bitcoin is a cryptocurrency. It is a decentralized digital currency without a central bank or single administrator that can be sent from user to user on the peer-to-peer bitcoin network without the need for intermediaries.(from https://en.wikipedia.org/wiki/Bitcoin)
    * cryptocurrency
    * decentralized
    * peer-to-peer bitcoin network
* Brief history
    * 2008 - The Bitcoin White Paper is Released
    * Jan 2009 - First Bitcoin Block is Mined
    * Jan 2009 - First Bitcoin Transaction
    * Oct 2009 - First listed Dollar to Bitcoin Exchage Rate
    * May 2010 - First Real World Bitcoin Purchase
    * Feb 2011 - Silk Road Marketplace Opens
    * Nov 2013 - Price hits $1242 for a single Bitcoin
    * Feb 2014 - Mt.Gox gets hacked, $450 million missing 
    * Dec 2014 - Microsoft adds Bitcoin Payments to Xbox live
* Cryptographic hash function (Backbone of the Bitcoin Network)
    * MD5(MD4);SHA-256(SHA-1);RIPEMD,BLAKE,Skein
    * first application: Digital Signatures
    * puzzle friendly: difficult to solve,easy to verify    
    * Cryptographic is very important!
        * determined: same input same output
        * computationally efficient
        * Collision resistance: different inputs,different output. hard to find two inputs that actually map to same output.
        * hiding information about input
        * Digest should look random
    * ref1: https://youtu.be/0WiTaBI82Mc
* Digital Signature
    * a digital signature scheme is a triple of probabilistic polynomial time algorithms, (G, S, V), satisfying:
        G (key-generator) generates a public key (pk), and a corresponding private key (sk), on input 1n, where n is the security parameter.
        S (signing) returns a tag, t, on the inputs: the private key (sk), and a string (x).
        V (verifying) outputs accepted or rejected on the inputs: the public key (pk), a string (x), and a tag (t).
    * ref: https://en.wikipedia.org/wiki/Digital_signature
* Merkle Tree
    * In cryptography and computer science, a hash tree or Merkle tree is a tree in which every leaf node is labelled with the cryptographic hash of a data block, and every non-leaf node is labelled with the hash of the labels of its child nodes. 
    * Block chain is a linked list using hash pointers.
    * Proof of membership (Proof of inclusion):
        * Merkle proof: find the position of TX,and calculate the root hash. Make the validation of caculated root hash. Complexity: O(log(n))
    * Proof of non-membership:
        * Send all the struction of trees to light node, check it. complexity: O(n)
        * Sorted Merkle Tree: is not used in Bitcoin,because Bitcoin donot need proof of non-membership. Complexity: O(log(n))
    * ref: https://en.wikipedia.org/wiki/Merkle_tree
* UTXO
    * UTXO: Unspent Transaction Output
    * goal: check double spending 
    * a TX has many inputs and many outputs,but which statisfies: 
        * all the TX come from coinbase
        * all the TX inputs come from UTXO outputs of one or many TXs except TX of coinbase
        * total inputs = total outputs
* Script model in Bitcoin 
    * only stack: LIFO, Last In First Out. https://zh.wikipedia.org/wiki/%E5%A0%86%E6%A0%88
    * P2PKH(Pay to Public Key Hash) is most common. P2PKH: <sig> <PubK> DUP HASH160 <PubKHash> EQUALVERIFY CHECKSIG ref:
    * P2SH(Pay to script hash): used in MultiSig. P2SH: HASH160 PUSHDATA(goal script hash) EQUAL ref:https://en.bitcoin.it/wiki/Pay_to_script_hash
    * Proof of Burn: First scene:Burn Bitcoin and get some AltCoins(Alternative Coin). Second scene: digital commitment(hash the commitment content)
    * ref https://en.bitcoin.it/wiki/Script
    * CHECKMULTISIG:has a bug,so push a 0 to stack first.
* Security in Bitcoin
    * Cryptography: source is random
    * Consensus in BitCoin: legal identity ref: https://zh.wikipedia.org/wiki/%E5%85%B1%E8%AD%98%E6%A9%9F%E5%88%B6
    * Possible Attack
        * double spending attack: longest valid chain
        * sybil attack
        * forking attack: six confirmation
        * selfish mining
* Principle in Designing Bitcoin
    * simple,robust but not efficient
* ref1: https://youtu.be/5fSOd431l6A
* ref2: https://bitcoin.org/bitcoin.pdf

Ethereum

* Block Chain Version 2.0
* Smart Contract
    * What is Smart Contract? 
        * Smart Contract is a piece of code running in Block Chain. The code defines the content of contract. (by ZhenXiao)
        * A smart contract is a computer protocol intended to digitally facilitate, verify, or enforce the negotiation or performance of a contract. Smart contracts allow the performance of credible transactions without third parties. These transactions are trackable and irreversible.
        ref:https://en.wikipedia.org/wiki/Smart_contract
    * smart contract account: nonce(count number of transaction);balance;storageRoot(datastructure:MPT);codeHash
* EVM(Ethereum Virtual Machine)
    * Goal: Enforce Consistency. Just like JVM.
    * What is EVM?
        The Ethereum Virtual Machine (EVM) is a powerful, sandboxed virtual stack embedded within each full Ethereum node, responsible for executing contract bytecode. Contracts are typically written in higher level languages, like Solidity, then compiled to EVM bytecode.
    * Process
        * Smart contracts are often written in a programming language(Solidity,Vyper,Bamboo;Serpent,Mutan).
        * Smart contract languages like Solidity cannot be executed by the EVM directly. Instead, they are compiled to low-level machine instructions (called opcodes).
    * Opcodes
        * Stack-manipulating opcodes (POP, PUSH, DUP, SWAP)
        * Arithmetic/comparison/bitwise opcodes (ADD, SUB, GT, LT, AND, OR)
        * Environmental opcodes (CALLER, CALLVALUE, NUMBER)
        * Memory-manipulating opcodes (MLOAD, MSTORE, MSTORE8, MSIZE)
        * Storage-manipulating opcodes (SLOAD, SSTORE)
        * Program counter related opcodes (JUMP, JUMPI, PC, JUMPDEST)
        * Halting opcodes (STOP, RETURN, REVERT, INVALID, SELFDESTRUCT)
    * Bytecode
        * In order to efficiently store opcodes, they are encoded to bytecode. Every opcode is allocated a byte (for example; STOP is 0x00). 
    * ref https://medium.com/mycrypto/the-ethereum-virtual-machine-how-does-it-work-9abac2b7c9e
* State Transition in Ethereum
    The Ethereum state transition function, APPLY(S,TX) -> S' can be defined as follows:
    1. Check if the transaction is well-formed (ie. has the right number of values), the signature is valid,
    and the nonce matches the nonce in the sender's account. If not, return an error.
    2. Calculate the transaction fee as STARTGAS * GASPRICE, and determine the sending address from
    the signature. Subtract the fee from the sender's account balance and increment the sender's
    nonce. If there is not enough balance to spend, return an error.
    3. Initialize GAS = STARTGAS, and take off a certain quantity of gas per byte to pay for the bytes in
    the transaction.
    4. Transfer the transaction value from the sender's account to the receiving account. If the receiving
    account does not yet exist, create it. If the receiving account is a contract, run the contract's code
    either to completion or until the execution runs out of gas.
    5. If the value transfer failed because the sender did not have enough money, or the code execution
    ran out of gas, revert all state changes except the payment of the fees, and add the fees to the
    miner's account.
    6. Otherwise, refund the fees for all remaining gas to the sender, and send the fees paid for gas
    consumed to the miner.
    * ref: https://blockchainlab.com/pdf/Ethereum_white_paper-a_next_generation_smart_contract_and_decentralized_application_platform-vitalik-buterin.pdf
* State Management
    * Ethereum is a state machine based on the transaction.
    * The state in Ethereum actually is data store locally in form of state tries.
    * Account-based ledger (Bitcoin: Transaction-based ledger,UTXO) 
    * externally owned account: nonce(count number of using the account);balance;
    * smart contract account: nonce(count number of transaction);balance;storageRoot(datastructure:MPT);codeHash
    * three tries local 
        * state trie
        * transaction trie
        * receipt trie
    * structure in three tries 
        * data storage in (key,value)
        * state trie:key - address of ethereum;160 bits; value - RLP(nonce;balance;storageRoot;codeHash)
        * MPT and bloom filter.
    * Some Terminology
        * MPT:Merkle Patricia Tree/Trie(compressed hash pointer retrieval)
        * RLPRecursive Length Prefix(method of Serialization:nested array of bytes)
* Possible Attack
    * Re-entrancy Attack: clear state first!
* ref1: https://github.com/ethereum/wiki/wiki/White-Paper
* ref2: https://ethereum.github.io/yellowpaper/paper.pdf
* ref3: https://solidity.readthedocs.io/en/v0.4.24/index.html

cosmos

* Why cosmos?
    * Goal of cosmos: solve the prolem of application of high speed transaction and high throughout.
    * Bitcoin 
        * disadvantage1: Script language - Scrypt cannot do complex thing,such as decentralized predict market.
        * disadvantage2: speed of handle transaction is slow: about 7 txs/second.
    * Ethereum 
        * disadvantage1: Solidity language is apt to have mistakes and being attacked.
        * disadvantage2: speed of handle transaction is slow: about 15 txs/second.
        * disadvantage3: smart contract is hard to upgrade.
* Tendermint: Cosmos consensus algorithm (ref https://github.com/tendermint/tendermint)
    * Goal of Tendermint: born in 2014, to solve the problem of speed, scalability and enrvironment of PoW consensus.
    * Idea of Tendermint 
        * Add Validator,voting power(in a PoS application such as the Comos Hub,the voting power may be determined by the amount of staking tokens bonded as collateral)
        * Resist sybil attack using Pledge(locked in blockchain system).
        * Vote: Propose,Prevote,Precommit,Commit,NewHeight
    * Feature of Tendermint
        * application-agnostic: every Blockchain can use.
        * BFT: Byzantine Fault Tolerance.
        * resist sybil attack using PoS algorithm.
    * Differences compared to Satoshi Nakamoto consensusm,ethash consensus
        * Probability of being the canonical chain is 100% instead of high probability.
        * Fixed Validators instead of variable validators.
        * Fixed proposal instead of no proposal
        * Fixed timeout mechanism
        * disadvantage1: temporary validators cannot be permitted to quit or enter.
        * disadvantage2: system shuold maitain a same timing system
    * performance of Tendermint
        * block time can be 1 second, speed of transaction: 1000txs/second
        * Finality is immediate if there is less than 1/3 validators in system.
* Inter Blockchain Communication(IBC)
    * The Hub and zones communicate with each other. 
    * To move a packet from one blockchain to another:
        * a proof is posted on the receiving chain. 
        * The proof states that the sending chain published a packet for the alleged destination. 
        * For the receiving chain to check this proof, it must be able keep up with the sender’s block headers. 
        * This mechanism is similar to that used by sidechains, which requires two interacting chains to be aware of one another via a bidirectional stream of proof-of-existence datagrams (transactions).
    * The IBC protocol can naturally be defined using two types of transactions: 
        * IBCBlockCommitTx transaction: allows a blockchain to prove to any observer of its most recent block-hash.
        * IBCPacketTx transaction: allows a blockchain to prove to any observer that the given packet was indeed published by the sender’s application, via a Merkle-proof to the recent block-hash.
* Application Blockchain Interface (ABCI) 
    * Blockchains are systems for multi-master state machine replication. ABCI is an interface that defines the boundary between the replication engine (the blockchain), and the state machine (the application). Using a socket protocol, a consensus engine running in one process can manage an application state running in another.
    * ABCI allows for blockchain applications to be programmed in any language, not just the programming language that the consensus engine is written in. 
    * Additionally, ABCI makes it possible to easily swap out the consensus layer of any existing blockchain stack.
    * Example of Bitcoin: the ABCI application would be responsible for
        * Maintaining the UTXO database
        * Validating cryptographic signatures of transactions 
        * Preventing transactions from spending non-existent funds 
        * Allowing clients to query the UTXO database
    * ref https://github.com/tendermint/abci

* ref1: https://cosmos.network/cosmos-whitepaper.pdf
* ref2: https://ethfans.org/posts/how-does-cosmos-work-part1

consensus

* Proof-of-Work(PoW)
    * Disadvantage
        * energe: electric power is wasted.
        * mining pool: decentralization is changing to centralization.
* Proof-of-stake(PoS) 
    * What is Proof of stake(PoS)?
        PoS is a method of securing a cryptocurrency network through requesting users to show ownership of a certain amount of currency.
    * Idea
        * add validators(token as pledge:determine the probability of chosen as validator)
        * mining block ---> Minting/Forging
    * advantages
        * cheap:decentralization
        * electric power is less
    * disadvantages
        * 51% attack: richer man become richer. Solve by:froze currency used for choose validator for some time.
        * refuse to be a validator. Solved by: choose more validators.
    * ref: https://en.bitcoinwiki.org/wiki/Proof-of-stake
* Delegated Proof of Stake (DPoS) 
    * Whast is DPoS?
        * DPoS is a consensus algorithm developed to secure a blockchain by ensuring representation of transactions within it.
        * DPoS is designed as an implementation of technology-based democracy, using voting and election process to protect blockchain from centralization and malicious usage.
    * advantages
        * DPoS coins are much more scalable than POW cryptocurrencies as they never start requiring high computing power and are generally approachable for users with poor equipment.
        * DPoS blockchains showed themselves to be faster than PoW and PoS-based blockchains.
        * DPoS coins are more democratic and inclusive than their alternatives. DPoS vs PoS offers more governance power to users with small stakes, * DPoS vs PoW does not require as much computing power and, therefore, is not so financially demanding on the user.
        As threshold to enter is very low, DPoS is largely considered to be the most decentralized approach to consensus mechanism.
        * DPoS is energy efficient and environmentally friendly.
        * DPoS networks have strong protection from double spend attack.
    * disadvantages
        * Successful existence of the network requires participation and coordination of genuinely interested community for effective governance of the panel of witnesses by voting them in and out.
        * DPoS systems are vulnerable to centralization as a number of witnesses is strictly limited.
        * DPoS blockchain is exposed to flaws of classic real-life voting. For example, DPoS users with small stakes can decide that their vote doesn't matter in comparison with votes of bigger stakeholders.
* ref1: https://zh.wikipedia.org/wiki/%E5%85%B1%E8%AD%98%E6%A9%9F%E5%88%B6